package com.theaf.core.rmq;

import com.theaf.core.annotation.MqConfig;
import com.theaf.core.utils.SmExceptionHelper;
import com.theaf.core.utils.SpringUtils;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.io.IOException;
import java.util.Arrays;

/**
 * @Author:songwenke
 * @Description:消费者注入扫描
 * @Date:create in 9:55 2018/3/27
 * @Modified By:
 **/
public class MQConsumerScanner implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Arrays.stream(bean.getClass().getInterfaces()).forEach(n->{
            if(!n.equals(MessageProcess.class)){
                throw SmExceptionHelper.sysCheckException("消息队列的消费者必须实现此接口：MessageProcess");
            }
        });
        MqConfig config = bean.getClass().getAnnotation(MqConfig.class);
        if(config!=null){
            MQAccessBuilder builder = new MQAccessBuilder((ConnectionFactory) SpringUtils.getBean("connectionFactory"));
            MessageConsumer messageConsumer = null;
            if(config.type()==1){//简单消息
                try {
                    messageConsumer = builder.buildMessageConsumer(null,"",config.topic(),(MessageProcess)bean);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{//广播消息
                try {
                    messageConsumer = builder.buildFanoutMessageConsumer(config.topic(),"",
                            config.topic()+ "_"+this.getClass().getName(),(MessageProcess)bean);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ThreadPoolConsumer.addConsumer(messageConsumer);
        }
        return null;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }
}
